"use client"

import { useState, useEffect } from "react"
import "./FavoritesPage.css"

function FavoritesPage() {
  const [favoriteComments, setFavoriteComments] = useState([])
  const [favoriteSeeds, setFavoriteSeeds] = useState([])
  const [activeTab, setActiveTab] = useState("comments")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(null)
  const [stats, setStats] = useState({
    totalComments: 0,
    totalSeeds: 0,
  })

  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    return {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": "application/json",
    }
  }

  const fetchFavoriteComments = async () => {
    try {
      setIsLoading(true)
      const userId = localStorage.getItem("userId")
      const response = await fetch(`/comments/favorites/list?userId=${userId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取收藏帖子失败")
      }

      const data = await response.json()
      if (data.result) {
        setFavoriteComments(data.rows["favoriteComments"])
        setStats((prev) => ({ ...prev, totalComments: data.rows["total"] }))
      } else {
        throw new Error(data.message || "获取收藏帖子失败")
      }
    } catch (err) {
      console.error("获取收藏帖子错误:", err)
      setError(err.message)
    } finally {
      setIsLoading(false)
    }
  }

  const fetchFavoriteTorrents = async () => {
    try {
      setIsLoading(true)
      const userId = localStorage.getItem("userId")

      // 第一步：获取收藏的种子ID列表
      const response = await fetch(`/favorite/userFavorites?user_id=${userId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取收藏种子失败")
      }

      const data = await response.json()
      if (data.result && data.rows && data.rows.torrent_ids) {
        const torrentIds = data.rows.torrent_ids
        setStats((prev) => ({ ...prev, totalSeeds: data.rows.count || torrentIds.length }))

        // 第二步：批量获取种子详情
        if (torrentIds.length > 0) {
          const torrentDetails = await fetchTorrentDetails(torrentIds)
          setFavoriteSeeds(torrentDetails)
        } else {
          setFavoriteSeeds([])
        }
      } else {
        setFavoriteSeeds([])
        setStats((prev) => ({ ...prev, totalSeeds: 0 }))
      }
    } catch (err) {
      console.error("获取收藏种子错误:", err)
      setError(err.message)
    } finally {
      setIsLoading(false)
    }
  }

  // 新增函数：批量获取种子详情
  const fetchTorrentDetails = async (torrentIds) => {
    try {
      // 并发请求所有种子详情，限制并发数量避免服务器压力
      const batchSize = 5 // 每批处理5个请求
      const torrentDetails = []

      for (let i = 0; i < torrentIds.length; i += batchSize) {
        const batch = torrentIds.slice(i, i + batchSize)
        const batchPromises = batch.map(async (torrentId) => {
          try {
            const response = await fetch(`/torrent/getTorrentDetails/${torrentId}`, {
              method: "GET",
              headers: getAuthHeaders(),
            })

            if (!response.ok) {
              console.warn(`获取种子${torrentId}详情失败`)
              return null
            }

            const data = await response.json()
            if (data.result && data.rows) {
              return {
                ...data.rows,
                favoriteTime: new Date().toISOString(), // 添加收藏时间，实际应该从收藏接口获取
              }
            }
            return null
          } catch (error) {
            console.warn(`获取种子${torrentId}详情出错:`, error)
            return null
          }
        })

        const batchResults = await Promise.all(batchPromises)
        torrentDetails.push(...batchResults.filter((detail) => detail !== null))

        // 添加小延迟避免请求过于频繁
        if (i + batchSize < torrentIds.length) {
          await new Promise((resolve) => setTimeout(resolve, 100))
        }
      }

      return torrentDetails
    } catch (error) {
      console.error("批量获取种子详情失败:", error)
      return []
    }
  }

  const handleCommentClick = (commentId) => {
    // 跳转到帖子详情页面
    window.location.href = `/comment/${commentId}`
  }

  const handleSeedClick = (seedId) => {
    // 跳转到种子详情页面
    window.location.href = `/download?torrent_id=${seedId}`
  }

  const formatDate = (dateString) => {
    if (!dateString) return "未知时间"
    return new Date(dateString).toLocaleString("zh-CN")
  }

  useEffect(() => {
    fetchFavoriteComments()
    fetchFavoriteTorrents()
  }, [])

  // 添加重试函数
  const retryFetch = () => {
    setError(null)
    if (activeTab === "comments") {
      fetchFavoriteComments()
    } else {
      fetchFavoriteTorrents()
    }
  }

  return (
    <div className="favorites-page">
      <div className="favorites-container">
        {/* 右侧收藏列表 */}
        <div className="favorites-content">
          <div className="content-header">
            <h2>我的收藏</h2>
            <div className="favorites-tab-buttons">
              <button
                className={`favorites-tab-button ${activeTab === "comments" ? "active" : ""}`}
                onClick={() => setActiveTab("comments")}
              >
                收藏帖子 ({stats.totalComments})
              </button>
              <button
                className={`favorites-tab-button ${activeTab === "seeds" ? "active" : ""}`}
                onClick={() => setActiveTab("seeds")}
              >
                收藏种子 ({stats.totalSeeds})
              </button>
            </div>
          </div>

          {isLoading && (
            <div className="loading">
              <div>正在加载收藏数据...</div>
            </div>
          )}

          {error && (
            <div className="error">
              <div>错误: {error}</div>
              <button className="retry-button" onClick={retryFetch}>
                重试
              </button>
            </div>
          )}

          {/* 收藏帖子列表 */}
          {activeTab === "comments" && (
            <div className="favorites-list">
              {favoriteComments.length > 0 ? (
                favoriteComments.map((comment) => (
                  <div key={comment.id} className="favorite-item" onClick={() => handleCommentClick(comment.id)}>
                    <div className="item-icon">📝</div>
                    <div className="item-content">
                      <h3 className="item-title">{comment.title || "帖子内容"}</h3>
                      <p className="item-desc">{comment.content?.substring(0, 100) + "..." || "暂无内容"}</p>
                      <div className="item-meta">
                        <span className="item-author">作者: {comment.author || "匿名"}</span>
                        <span className="item-time">收藏时间: {formatDate(comment.createdAt)}</span>
                      </div>
                    </div>
                    <div className="item-arrow">→</div>
                  </div>
                ))
              ) : (
                <div className="empty-state">
                  <div className="empty-icon">📝</div>
                  <p>暂无收藏的帖子</p>
                </div>
              )}
            </div>
          )}

          {/* 收藏种子列表 */}
          {activeTab === "seeds" && (
            <div className="favorites-list">
              {favoriteSeeds.length > 0 ? (
                favoriteSeeds.map((seed) => (
                  <div key={seed.torrentId} className="favorite-item" onClick={() => handleSeedClick(seed.torrentId)}>
                    <div className="item-icon">🌱</div>
                    <div className="item-content">
                      <h3 className="item-title">{seed.title || "种子文件"}</h3>
                      <p className="item-desc">
                        {seed.description?.substring(0, 100) + (seed.description?.length > 100 ? "..." : "") ||
                          "暂无描述"}
                      </p>
                      <div className="item-meta">
                        <span className="item-category">分类: {seed.category || "未分类"}</span>
                        <span className="item-tags">标签: {seed.tags || "无标签"}</span>
                        <span className="item-time">上传时间: {formatDate(seed.uploadTime)}</span>
                      </div>
                    </div>
                    <div className="item-arrow">→</div>
                  </div>
                ))
              ) : (
                <div className="empty-state">
                  <div className="empty-icon">🌱</div>
                  <p>暂无收藏的种子</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default FavoritesPage
